package com.huishu.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huishu.commons.exception.BaseException;
import com.huishu.commons.pojo.Result;
import com.huishu.commons.pojo.vo.FullReductionVO;
import com.huishu.commons.pojo.vo.GiveProductVO;
import com.huishu.commons.utlis.BeanUtils;
import com.huishu.commons.utlis.DateUtils;
import com.huishu.goods.mapper.ProductFullReductionMapper;
import com.huishu.goods.mapper.ProductGiveMapper;
import com.huishu.goods.mapper.ProductMapper;
import com.huishu.goods.pojo.dto.ProductFullReductionCreateDTO;
import com.huishu.goods.pojo.dto.ProductFullReductionPageDTO;
import com.huishu.goods.pojo.dto.ProductFullReductionUpdateDTO;
import com.huishu.goods.pojo.model.ProductFullReductionDO;
import com.huishu.goods.pojo.model.ProductGiveDO;
import com.huishu.goods.pojo.vo.ProductFullReductionPageVO;
import com.huishu.goods.pojo.vo.ProductFullReductionVO;
import com.huishu.goods.service.ProductFullReductionService;
import com.huishu.goods.service.ProductGiveService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author generator@ljj
 * @since 2023-04-10
 */
@Slf4j
@Service
public class ProductFullReductionServiceImpl extends ServiceImpl<ProductFullReductionMapper, ProductFullReductionDO> implements ProductFullReductionService {

    @Autowired
    @Qualifier("threadPoolTaskExecutor")
    private Executor executor;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductGiveMapper productGiveMapper;

    @Autowired
    private ProductGiveService productGiveService;

    @Override
    public Result<List<FullReductionVO>> find(List<Long> ids) {
        // 查询满减活动
        LambdaQueryWrapper<ProductFullReductionDO> queryWrapper = Wrappers.lambdaQuery(ProductFullReductionDO.class)
                .le(ProductFullReductionDO::getStartDate, new Date())
                .ge(ProductFullReductionDO::getEndDate, new Date());
        List<ProductFullReductionDO> productFullReductions = this.list(queryWrapper);
        if (CollectionUtils.isEmpty(productFullReductions)) {
            return Result.success(new ArrayList<>());
        }
        List<Long> fullReductionIds = productFullReductions.stream().map(ProductFullReductionDO::getId).collect(Collectors.toList());
        // 查询满减赠品
        List<GiveProductVO> giveProducts = productGiveMapper.findGiveByFullReductionIds(fullReductionIds);
        // 生成产品map
        Map<Long, List<GiveProductVO>> giveProductMap = giveProducts.stream().collect(Collectors.groupingBy(GiveProductVO::getFullReductionId));

        // 组合数据
        List<FullReductionVO> collect = productFullReductions.stream().map(productFullReductionDO -> {
            FullReductionVO fullReductionVO = BeanUtils.copyProperties(productFullReductionDO, FullReductionVO.class);
            List<GiveProductVO> giveProductVOS = giveProductMap.get(productFullReductionDO.getId());
            fullReductionVO.setGiveProducts(giveProductVOS == null ? new ArrayList<>() : giveProductVOS);
            return fullReductionVO;
        }).collect(Collectors.toList());
        return Result.success(collect);

    }

    @Transactional
    @Override
    public Result create(ProductFullReductionCreateDTO productFullReductionCreateDTO) {
        LambdaQueryWrapper<ProductFullReductionDO> qw = Wrappers.lambdaQuery(ProductFullReductionDO.class)
                .eq(ProductFullReductionDO::getFullPrice, productFullReductionCreateDTO.getFullPrice());
        ProductFullReductionDO one = this.getOne(qw);
        if (one != null) {
            return Result.fail("已经存在金额 " + productFullReductionCreateDTO.getFullPrice() + "的满减活动请勿重复添加!!");
        }

        ProductFullReductionDO productFullReductionDO = new ProductFullReductionDO();
        productFullReductionDO.setName(productFullReductionCreateDTO.getName());
        productFullReductionDO.setFullPrice(productFullReductionCreateDTO.getFullPrice());
        productFullReductionDO.setReducePrice(productFullReductionCreateDTO.getReducePrice());
        productFullReductionDO.setStartDate(DateUtils.parseStrToDate(productFullReductionCreateDTO.getStartDate(), DateUtils.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
        productFullReductionDO.setEndDate(DateUtils.parseStrToDate(productFullReductionCreateDTO.getEndDate(), DateUtils.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
        productFullReductionDO.setActiviPic(productFullReductionCreateDTO.getActiviPic());
        productFullReductionDO.setDesc(productFullReductionCreateDTO.getDesc());
        boolean save = this.save(productFullReductionDO);
        if (!save) {
            throw new BaseException("添加失败!!");
        }
        List<ProductGiveDO> productGives = productFullReductionCreateDTO.getProductGives();
        if(CollectionUtils.isNotEmpty(productGives)){
            List<ProductGiveDO> collect = productGives.stream().peek(productGiveDO -> {
                productGiveDO.setFullReductionId(productFullReductionDO.getId());
                productGiveDO.setType(2);
            }).collect(Collectors.toList());
            return productGiveService.saveBatch(collect) ? Result.success() : Result.fail();
        }
        return Result.success();
    }

    @Transactional
    @Override
    public Result modify(ProductFullReductionUpdateDTO productFullReductionUpdateDTO) {
        LambdaQueryWrapper<ProductFullReductionDO> qw = Wrappers.lambdaQuery(ProductFullReductionDO.class)
                .eq(ProductFullReductionDO::getFullPrice, productFullReductionUpdateDTO.getFullPrice())
                .ne(ProductFullReductionDO::getId, productFullReductionUpdateDTO.getId());
        ProductFullReductionDO one = this.getOne(qw);
        if (one != null) {
            return Result.fail("已经存在金额 " + productFullReductionUpdateDTO.getFullPrice() + "的满减活动请勿重复添加!!");
        }

        ProductFullReductionDO productFullReductionDO = new ProductFullReductionDO();
        productFullReductionDO.setId(productFullReductionUpdateDTO.getId());
        productFullReductionDO.setName(productFullReductionUpdateDTO.getName());
        productFullReductionDO.setFullPrice(productFullReductionUpdateDTO.getFullPrice());
        productFullReductionDO.setReducePrice(productFullReductionUpdateDTO.getReducePrice());
        productFullReductionDO.setStartDate(DateUtils.parseStrToDate(productFullReductionUpdateDTO.getStartDate(), DateUtils.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
        productFullReductionDO.setEndDate(DateUtils.parseStrToDate(productFullReductionUpdateDTO.getEndDate(), DateUtils.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
        productFullReductionDO.setActiviPic(productFullReductionUpdateDTO.getActiviPic());
        productFullReductionDO.setDesc(productFullReductionUpdateDTO.getDesc());
        boolean save = this.updateById(productFullReductionDO);
        if (!save) {
            throw new BaseException("添加失败!!");
        }
        LambdaQueryWrapper<ProductGiveDO> queryWrapper = Wrappers.lambdaQuery(ProductGiveDO.class)
                .eq(ProductGiveDO::getFullReductionId, productFullReductionDO.getId());
        productGiveService.remove(queryWrapper);
        List<ProductGiveDO> productGives = productFullReductionUpdateDTO.getProductGives();
        if(CollectionUtils.isNotEmpty(productGives)){
            List<ProductGiveDO> collect = productGives.stream().peek(productGiveDO -> {
                productGiveDO.setFullReductionId(productFullReductionDO.getId());
                productGiveDO.setType(2);
            }).collect(Collectors.toList());
            return productGiveService.saveBatch(collect) ? Result.success() : Result.fail();
        }
        return Result.success();
    }

    @Override
    public Result findById(Long id) {
        ProductFullReductionDO productFullReductionDO = this.getById(id);
        ProductFullReductionVO productFullReductionVO = BeanUtils.copyProperties(productFullReductionDO, ProductFullReductionVO.class);
        LambdaQueryWrapper<ProductGiveDO> queryWrapper = Wrappers.lambdaQuery(ProductGiveDO.class)
                .eq(ProductGiveDO::getFullReductionId, productFullReductionDO.getId());
        List<ProductGiveDO> productGiveDOS = productGiveService.list(queryWrapper);
        productFullReductionVO.setProductGives(productGiveDOS);
        return Result.success(productFullReductionVO);
    }

    @Override
    public Result delete(Long id) {
        boolean b = this.removeById(id);
        if (!b) {
            throw new BaseException("删除失败!!");
        }
        LambdaQueryWrapper<ProductGiveDO> queryWrapper = Wrappers.lambdaQuery(ProductGiveDO.class)
                .eq(ProductGiveDO::getFullReductionId, id);
        productGiveService.remove(queryWrapper);
        return Result.success();
    }

    @Override
    public Result pageList(ProductFullReductionPageDTO productFullReductionPageDTO) {
        Page<ProductFullReductionPageVO> page = new Page<>(productFullReductionPageDTO.getCurrPage(), productFullReductionPageDTO.getPageSize());
        return Result.success(this.baseMapper.pageList(page, productFullReductionPageDTO));
    }
}
